//
//  TestModel.m
//  RuntimeDemo
//
//  Created by 张敬 on 2019/10/14.
//  Copyright © 2019年 xiuxiu. All rights reserved.
//

#import "TestModel.h"
#import <objc/runtime.h>

@implementation TestModel

//运用runtime编写归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    //    [aCoder encodeObject:self.name forKey:@"name"];
    //    [aCoder encodeObject:self.age forKey:@"age"];
    
    unsigned int count;
    Ivar *ivarList = class_copyIvarList([self class], &count);
    for (unsigned int k = 0; k < count; k++) {
        const char *ivarName = ivar_getName(ivarList[k]);
        NSString *key = [NSString stringWithUTF8String:ivarName];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    free(ivarList);
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        
//        self.name = [coder decodeObjectForKey:@"name"];
//        self.age = [coder decodeObjectForKey:@"age"];
        
        unsigned int count;
        Ivar *ivarList = class_copyIvarList([self class], &count);
        for (unsigned int k = 0; k < count; k++) {
            const char *ivarName = ivar_getName(ivarList[k]);
            NSString *key = [NSString stringWithUTF8String:ivarName];
            id value = [coder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
    }
    return self;
}

@end
